"use strict";
/**
 * 生成hash
 */
const generateHash = () => {
  return (
    'xxxx_4xxx_yxxx'.replace(/[xy]/g, function (c) {
      var r = (Math.random() * 16) | 0,
        v = c == 'x' ? r : (r & 0x3) | 0x8
      return v.toString(16)
    }) + `_${new Date().getTime()}`
  )
}

function GetRandomNum(Min, Max) {
  var Range = Max - Min;
  var Rand = Math.random();
  return (Min + Math.round(Rand * Range));
}
var num = GetRandomNum(10000, 999999);
/**
 * 校验版本号
 * @param {*} version 版本号
 */
const isValidVersion = (version, env) => {
  var reg = /^(\d+)\.(\d+)\.(\d+)$/
  if (env === 'pro') {
    return reg.test(version)
  } else {
    return true
  }
}
/**
 * 加载脚本
 * @param {*} url  脚本url
 *  @param {*} id  id属性
 */
const useDynamicScript = async (url, id) => {
  if (!url) throw new Error('脚本url不能为空')
  return new Promise((resolve, reject) => {
    if (document.getElementById(id)) {
      resolve(false)
    } else {
      const element = document.createElement('script')
      element.src = url
      element.id = id
      element.type = 'text/javascript'
      // element.async = true
      element.onload = (e) => {
        resolve(true)
      }
      element.onerror = () => {
        reject(false)
      }
      document.head.appendChild(element)
    }
  })
}
/**
 * 加载版本配置文件 返回最新版本号
 * @param {*} url 版本配置文件地址
 * @param {*} scope 需要动态加载的服务的name
 * @param {*} appoint 指定版本
 */
const fetchVersion = async (url, scope, env, appoint = '') => {
  const src = url
  // if (env === 'pro') {
  //   src = `${url.slice(0,-3)}_v${GetRandomNum(10000,999999)}.js`
  // }
  await useDynamicScript(src, `${scope}_version`)
  const versionConfig = window[`${scope}_meta`].versionConfig
  const versions = versionConfig[env].versionRecord
  const versionSwitchObj = sessionStorage.getItem('versionSwitchObj') ? JSON.parse(sessionStorage.getItem('versionSwitchObj')) : {}
  if (versionSwitchObj[`${scope}_meta_version`]) return versionSwitchObj[`${scope}_meta_version`]
  if (appoint && versions.includes(appoint)) return appoint
  return versions.find((item) => isValidVersion(item, env))
}

/**
 * 加载模块
 * @param {*} scope 服务名
 * @param {*} module 子应用导出模块路径 例： ./bootstrap.js
 */
const loadComponent = (scope, module) => {
  return async () => {
    // Initializes the share scope. This fills it with known provided modules from this build and all remotes
    await __webpack_init_sharing__('default')
    const container = window[scope] // or get the container somewhere else
    // Initialize the container, it may provide shared modules
    await container.init(__webpack_share_scopes__.default)
    const factory = await window[scope].get(module)
    const Module = factory()
    return Module
  }
}
/**
 * 加载远程模块脚本
 * @param {*} scope 服务名
 * @param {*} publicPath 远程模块脚本地址
 * @param {*} appoint 指定当前加载模块版本
 */
const loadComponentScript = async (scope, publicPath, env, appoint) => {
  const versionPath = `${publicPath}${scope}_version.js`
  const version = await fetchVersion(versionPath, scope, env, appoint) // 加载版本配置文件 返回版本号
  const scopePath = `${publicPath}${scope}_${version}.js`
  const loadRes = await useDynamicScript(scopePath, `${scope}_${version}`)
  // eslint-disable-next-line no-console
  loadRes && console.log(`远程版本号:【 ${version} 】\n加载模块:【 ${scope} 】\n远程模块地址:【 ${scopePath} 】`)
}

module.exports = {
  loadComponentScript,
  loadComponent
};